<?php
/**
 * Created by PhpStorm.
 * User: 戎大富
 * Date: 2019/3/21
 * Time: 10:09
 * 发现
 */
namespace app\api\controller;
use think\Db;
class Home extends Base {
    /**
     * 异地登录验证
     * @return string
     */
    public function __construct()
    {
        extract(input());
        $auth = $this->checkAll($user_id,$time,$value,$reqKey);
        if($auth == 112){
            echo json_encode(['status'=>301,'msg'=>$this->otherLogin]);
            exit;
        }elseif($auth == 110){
            echo json_encode(['status' => 302, 'msg' => $this->frost]);
            exit;
        }
        
    }

    /**
     * 获取轮播图：getBanner
     */
    public function getBanner(){
        extract(input());
        $data = Db::name('lunbo')
            ->where(['lunbo_type'=>1, 'lunbo_sta' => 1])
//            ->field(['lunbo_id','lunbo_image'])
            ->order('lunbo_sort DESC')
            ->limit (5)
            ->select();
        return json(['status'=>200,'msg'=>$data]);
    }

    /**
     * 获取轮播图内容：getBannerContent
     */
    public function getBannerContent(){
        extract(input());
        $data = Db::name('lunbo')
            ->where(['lunbo_id'=>$lunbo_id])
            ->find();
        return json(['status'=>200,'msg'=>$data]);
    }

    /***
     * $user_id
     * @return \think\response\Json
     * 签到首页
     */
    public function signHome(){
        extract(input());
        //1、先去签到
        $res = $this->signIn($user_id);
        if($res === false){
            return json(array('status' => 0, 'msg' => '签到失败，请重试'));
        }else{
            if($res === true){
                $honor = '';
            }else{
                $honor = $res;
            }
            $where = array();
            $where['si_user_id'] = $user_id;
            //2、展示几条（最多7条）
            $last_day = Db::table('up_sign_in')
                ->where($where)
                ->order('si_date DESC')
                ->find();
            $limit = 7;
            if($last_day['si_day'] < 7){
                $limit = $last_day['si_day'];
            }

            $res = Db::table('up_sign_in')
                ->where($where)
                ->order('si_date DESC')
                ->limit(0,$limit)
                ->select();
            $today_score = $res[0]['si_score'];
            $data = array_reverse($res);
            if($limit != 7){
                $score = Db::table('up_sign_config')->where('id',1)->value('score');
                $more = 7-$limit;
                for($i=1;$i<=$more;$i++){
                    $data[$limit+$i-1]['si_day'] = $limit+$i;
                    $data[$limit+$i-1]['si_status'] = 2;
                    if($limit+$i >= 3){
                        $data[$limit+$i-1]['si_score'] = $score*3;
                    }else{
                        $data[$limit+$i-1]['si_score'] = $score*($limit+$i);
                    }
                }
            }
            return json(array('status' => 200, 'msg' => $data, 'honor' => $honor, 'today_score' => $today_score));
        }

    }
    /***
     * range：1是全班  2是全校  3是全国
     * type：1是周  2是月  3是年
     * @return \think\response\Json
     * 排行榜
     */
    public function userTop(){
        extract(input());
        if($type == 1){
            $field = 'user_exp_week';
        }elseif ($type == 2){
            $field = 'user_exp_month';
        }else{
            $field = 'user_exp_year';
        }
        if($range == 1){
            $where = array();
            $where['gs_user_id'] = $user_id;
            $cid = Db::table('up_grade_class')
                ->where($where)
                ->find();
            if(!$cid){
                return json(array('status' => 0, 'msg' => '请去完善资料'));
            }else{
                if($cid['gs_school_id'] == '' || $cid['gs_grade_id'] == '' || $cid['gs_class_id'] == ''){
                    return json(array('status' => 0, 'msg' => '请去完善资料'));
                }
            }
            $uids = Db::table('up_grade_class')
                ->where('gs_school_id',$cid['gs_school_id'])
                ->where('gs_grade_id',$cid['gs_grade_id'])
                ->where('gs_class_id',$cid['gs_class_id'])
                ->where('gs_role',1)
                ->column('gs_user_id');
            $data = Db::table('up_u_user u')
                ->join ('up_grade_class gc','u.user_id = gc.gs_user_id','LEFT')
                ->join ('up_class c','gc.gs_class_id = c.class_id','LEFT')
                ->join ('up_grade g','gc.gs_grade_id = g.grade_id','LEFT')
                ->join ('up_school sc','gc.gs_school_id = sc.school_id','LEFT')
                ->join ('up_area a','u.user_shi = a.district_id','LEFT')
                ->where('user_id','in',$uids)
                ->where("$field",'>',0)
                ->field("user_id,user_username,user_image,$field as user_exp,district,school_name,grade_name,class_name,user_level")
                ->order("$field DESC")
                ->page($page,20)
                ->select();
        }else{
            $where = array();
            $where["$field"] = array('>',0);
            $where["user_type"] = 1;
            if($range == 2){
                $sid = Db::table('up_u_user')
                    ->where('user_id',$user_id)
                    ->value('user_school');
                if(!$sid){
                    return json(array('status' => 0, 'msg' => '请去完善资料'));
                }
                $where['user_school'] = $sid;
            }
            $data = Db::table('up_u_user u')
                ->join ('up_grade_class gc','u.user_id = gc.gs_user_id','LEFT')
                ->join ('up_class c','gc.gs_class_id = c.class_id','LEFT')
                ->join ('up_grade g','gc.gs_grade_id = g.grade_id','LEFT')
                ->join ('up_school sc','gc.gs_school_id = sc.school_id','LEFT')
                ->join ('up_area a','u.user_shi = a.district_id','LEFT')
                ->where($where)
                ->field("user_id,user_username,user_image,$field as user_exp,district,school_name,grade_name,class_name,user_level")
                ->order("$field DESC")
                ->page($page,20)
                ->select();
        }
        if($page > 5){
            $data = array();
        }
        if($data){
            foreach ($data as $k=>$v){
                if($v['user_level'] > 4){
                    $data[$k]['user_level'] = $v['user_level'] - 1;
                }
                $data[$k]['level'] = $this->getUserExpLevel ($v['user_id'])['el_name'];
            }
        }
        return json(array('status' => 200, 'msg' => $data));
    }

    public function userSeeTopInfo()
    {
        $data = Db::table('up_u_user u')
            ->join ('up_exp_level l','u.user_level = l.el_id','LEFT')
            ->where('user_id',$_POST['uid'])
            ->field('user_id,user_username,user_image,user_gender,user_age,user_exp,user_integral,user_y_m,el_name')
            ->find();
        $ym = explode('-',$data['user_y_m']);
        $data['year'] = $ym[0];
        $data['month'] = $ym[1];
        $data['readnum'] = Db::table('up_reading_book_pass')
            ->where('rbp_user_id',$_POST['uid'])
            ->count();
        $data['el_name'] = $this->getUserExpLevel ($_POST['uid'])['el_name'];
        return json(array('status' => 200, 'msg' => $data));
    }

    /***
     *
     * 用户的勋章情况
     */
    public function userHonors(){
        extract(input());
        $hids = Db::table('up_u_user')
            ->where('user_id',$user_id)
            ->value('user_honor');
        $hids = trim($hids,',');
        $data = Db::table('up_honor h')
            ->join ('up_coupon c','h.coupon_id = c.coupon_id','LEFT')
            ->field('h.*,c.coupon_name,c.coupon_price')
            ->select();
        if($hids){
            $hids = explode(',',$hids);
        }else{
            $hids = array(0);
        }
        foreach ($data as $k=>$v){
            $data[$k]['have'] = 0;
            if(in_array($v['id'],$hids)){
                $data[$k]['have'] = 1;
            }
        }
        $last_names = array_column($data,'have');
        array_multisort($last_names,SORT_DESC,$data);
        return json(array('status' => 200, 'msg' => $data));
    }

    //--------------------------------------------阅读对战----------------------------------------------
    /***
     *
     * 阅读闯关
     */
    public function userReading(){
        extract(input());
        $user = Db::table('up_u_user')
            ->where('user_id',$user_id)
            ->field('user_id,user_wanshan,user_default_book,user_pass_one,user_type,user_grade,user_status')
            ->find();
        $seesee = $this->getUserStatusForSee($user_id);
        if($seesee['status'] != 200){
            return json($seesee);
        }
        //1、如果没有完善资料，则不能进入此版块
        if($user['user_type'] == 2 && $user['user_wanshan'] == 1){
            return json(array('status' => 0, 'msg' => '您还没有完善资料'));
        }else{
            if($user['user_type'] == 1 && $user['user_wanshan'] == 1){
                $myBookIds = Db::table('up_grade')
                    ->where('grade_id',$user['user_grade'])
                    ->value('grade_books');
            }else{
                $myBookIds = trim($user['user_default_book'],',');
            }
            if(empty($myBookIds)){
                return json(array('status' => 200, 'msg' => array()));
            }
            $where = [
                'rb_status'=>1
            ];
            if($user['user_pass_one'] == 1){//未通关任一本
                $where['rb_id']=array('in',$myBookIds);
            }else{
                if($user['user_type'] == 1){
                    $where['rb_grade_id'] = $user['user_grade'];
                }
            }
            if(isset($keyword) && $keyword){
                $where['rb_name']=array('like','%'.$keyword.'%');
            }else{
                $keyword = '';
            }
            $books = Db::table('up_reading_book')
                ->where(function ($q) use ($where){
                    $q->where($where);
                })
                ->whereOr(function ($q) use ($myBookIds,$keyword){
                    $q->where('rb_status',1)->where('rb_id','in',$myBookIds);//->where('rb_name','like','%'.$keyword.'%');
                })
                ->field('rb_id,rb_name,rb_image')
                ->page($page,21)
                ->select();
            $havePass = Db::table('up_reading_book_pass')->where('rbp_user_id',$user_id)->column('rbp_book_id');
            $mybook = Db::table('up_my_book')->where('mb_user_id',$user_id)->column('mb_book_id');
            foreach ($books as $k=>$v){
                $books[$k]['pass'] = 1; //1代表没有通关，2代表已经通关
                $books[$k]['mybook'] = 1; //1代表没有加入书架，2代表已经加入书架
                if($havePass){
                    if(in_array($v['rb_id'],$havePass)){
                        $books[$k]['pass'] = 2;
                    }
                }
                if($mybook){
                    if(in_array($v['rb_id'],$mybook)){
                        $books[$k]['mybook'] = 2;
                    }
                }
            }
            return json(array('status' => 200, 'msg' => $books));
        }
    }
    public function searchBooks()
    {
        extract(input());
        $user = Db::table('up_u_user')
            ->where('user_id',$user_id)
            ->field('user_id,user_wanshan,user_default_book,user_pass_one,user_type,user_grade,user_status')
            ->find();
        $array = array();
        if($user['user_pass_one'] == 1){
            return json(array('status' => 200, 'msg' => $array));
        }else{
            if(isset($keyword) && $keyword){
                $books = Db::table('up_reading_book')
                    ->where('rb_status',1)
                    ->where('rb_name','like','%'.$keyword.'%')
                    ->field('rb_id,rb_name,rb_image')
                    ->page($page,21)
                    ->select();
                return json(array('status' => 200, 'msg' => $books));
            }else{
                return json(array('status' => 200, 'msg' => $array));
            }

        }
    }
    /***
     * 我的书架
     */
    public function myAddBooks(){
        extract(input());
        $where = [
            'rb_status'=>1,
            'mb_user_id'=>$user_id
        ];
        if(isset($keyword) && $keyword){
            $where['rb_name']=array('like','%'.$keyword.'%');
        }
        $books = Db::table('up_my_book mb')
            ->join ('up_reading_book b','mb.mb_book_id = b.rb_id','LEFT')
            ->where($where)
            ->field('rb_id,rb_name,rb_image')
            ->page($page, 21)
            ->select();
        $havePass = Db::table('up_reading_book_pass')->where('rbp_user_id', $user_id)->column('rbp_book_id');
        foreach ($books as $k => $v) {
            $books[$k]['pass'] = 1;//1代表没有通关，2代表已经通关
            if ($havePass) {
                if (in_array($v['rb_id'], $havePass)) {
                    $books[$k]['pass'] = 2;
                }
            }
        }
        return json(array('status' => 200, 'msg' => $books));
    }
    /***
     * 添加某本书到我的书架或取消
     */
    public function addOrDelBooksFromMy(){
        extract(input());
        $passone = Db::table('up_u_user')->where('user_id',$user_id)->value('user_pass_one');
        if($passone == 1){
            return json(array('status' => 100, 'msg' => '您还没有通关过任意一本书'));
        }
        $have = Db::table('up_my_book')
            ->where('mb_user_id', $user_id)
            ->where('mb_book_id', $rb_id)
            ->find();
        if($have){
            $res = Db::table('up_my_book')
                ->where('mb_user_id', $user_id)
                ->where('mb_book_id', $rb_id)
                ->delete();
        }else{
            $res = Db::table('up_my_book')
                ->insert(['mb_user_id'=>$user_id,'mb_book_id'=>$rb_id]);
        }
        if($res){
            return json(array('status' => 200, 'msg' => '操作成功'));
        }else{
            return json(array('status' => 100, 'msg' => '操作失败'));
        }
    }
    /***
     * 进入某个书本的详情:bookHome
     * rb_id：书本id
     */
    public function bookHome(){
        extract(input());
        //1、人数先加一
        $plus = Db::table('up_peple_gamenum')
            ->where('userid',$user_id)
            ->where('bookid',$rb_id)
            ->find();
        if(!$plus){
            Db::table('up_reading_book')->where('rb_id',$rb_id)->setInc('rb_num');
            Db::table('up_peple_gamenum')->insert(['userid'=>$user_id,'bookid'=>$rb_id]);
        }
        //2、书籍信息
        $book = Db::table('up_reading_book b')
            ->join ('up_grade g','b.rb_grade_id = g.grade_id','LEFT')
            ->where('rb_id',$rb_id)
            ->field('b.*,grade_name')
            ->find();
        //3、关卡信息
        $game = Db::table('up_reading_game')
            ->where('rg_rb_id',$rb_id)
            ->order('rg_order ASC')
            ->select();
        $mypass = Db::table('up_reading_game_pass')
            ->where('rgp_book_id',$rb_id)
            ->where('rgp_user_id',$user_id)
            ->column('rgp_game_id');
        $can = 0;
        if($game){
            foreach ($game as $k=>$v){
                if(in_array($v['rg_id'],$mypass)){
                    $game[$k]['have'] = 1;//已经通关了
                }else{
                    $can++;
                    if($can == 1){
                        $game[$k]['have'] = 2;//未通关可以答题
                    }else{
                        $game[$k]['have'] = 3;//未通关不可以答题
                    }
                }
            }
        }
        $have = Db::table('up_my_book')
            ->where('mb_user_id',$user_id)
            ->where('mb_book_id',$rb_id)
            ->find();
        $book['havemy'] = 1; //没有在我的书架里
        if($have){
            $book['havemy'] = 2; //在我的书架里
        }
        return json(array('status' => 200, 'msg' => $book,'game'=>$game));
    }

    /**
     * 某本书的班级学生通关情况（老师）
     * @return \think\response\Json
     */
    public function bookStuTopInfo()
    {
        extract(input());
        $seesee = $this->getUserStatusForSee($user_id);
        if($seesee['status'] != 200){
            return json($seesee);
        }
        $class = Db::table('up_grade_class')
            ->join('up_grade', 'grade_id = gs_grade_id', 'left')
            ->join('up_class', 'class_id = gs_class_id', 'left')
            ->field('up_grade_class.*, grade_name, class_name')
            ->where('gs_user_id', $user_id)
            ->group('gs_grade_id, gs_class_id')
            ->select();
        if($class){
            foreach ($class as $k=>$val){
                $class[$k]['number'] = 0;
                $class[$k]['nonono'] = 0;
                //学生信息
                $student = Db::table('up_grade_class c')
                    ->join('up_u_user u', 'u.user_id = c.gs_user_id', 'left')
                    ->join('up_exp_level l', 'u.user_level = l.el_id', 'left')
                    ->field('user_id, user_username, user_image, user_age, user_gender,el_name')
                    ->where('gs_school_id', $val['gs_school_id'])
                    ->where('gs_class_id', $val['gs_class_id'])
                    ->where('gs_grade_id', $val['gs_grade_id'])
                    ->where('gs_role', 1)
                    ->select();
                if($student){
                    $allstu = count($student);
                    $uids = array_column($student, 'user_id');
                    $pass_ids = Db::table('up_reading_book_pass')
                        ->where('rbp_book_id',$rb_id)
                        ->where('rbp_user_id','in',$uids)
                        ->column('rbp_user_id');
                    foreach ($student as $kk=>$vv){
                        $student[$kk]['pass'] = 1; //此学生未通过
                        if($pass_ids){
                            if(in_array($vv['user_id'],$pass_ids)){
                                $class[$k]['number'] += 1; //此班级通关人数加1
                                $student[$kk]['pass'] = 2; //此学生已通过
                            }
                        }
                    }
                    $class[$k]['nonono'] = $allstu - $class[$k]['number'];
                }
                $class[$k]['student'] = $student;
            }
        }
        return json(['status'=>200,'msg'=>$class]);
    }
    /***
     * 退出时人数减去1
     * 阅读闯关
     */
    public function outBookHome(){
        extract(input());
        //1、人数先加一
        $plus = Db::table('up_peple_gamenum')
            ->where('userid',$user_id)
            ->where('bookid',$rb_id)
            ->find();
        if($plus){
            Db::table('up_reading_book')->where('rb_id',$rb_id)->setDec('rb_num');
            $zero = Db::table('up_reading_book')->where('rb_id',$rb_id)->value('rb_num');
            if($zero < 0){
                Db::table('up_reading_book')->where('rb_id',$rb_id)->setField('rb_num',0);
            }
            Db::table('up_peple_gamenum')
                ->where('userid',$user_id)
                ->where('bookid',$rb_id)
                ->delete();
        }
        return json(array('status' => 200, 'msg' => 'ok'));
    }
    /***
     * 某个关卡的题:getGameSubjects
     * rg_id：关卡的id
     * rb_id：书的id
     * again：如果是失败再来一次：24小时之内免费再来一次
     * 阅读闯关
     */
    public function getGameSubjects(){
        extract(input());
        //------------------------以防万一进到此页（是否已通关）start----------------------
        $pass = Db::table('up_reading_book_pass')
            ->where('rbp_user_id',$user_id)
            ->where('rbp_book_id',$rb_id)
            ->find();
        if($pass){
            return json(array('status' => 0, 'msg' => '此书您已经通关了'));
        }
        //------------------------以防万一进到此页（是否已通关）start----------------------
        $pass = Db::table('up_reading_game_pass')
            ->where('rgp_user_id',$user_id)
            ->where('rgp_game_id',$rg_id)
            ->find();
        if($pass){
            return json(array('status' => 0, 'msg' => '此关您已经通过了'));
        }
        //------------------------以防万一进到此页（是否已通关）start----------------------
        //------------------------以防万一进到此页（是否已通关）start----------------------
        //-----------------
//        $today = date('Y-m-d H:i:s');
//        $time_24 = date("Y-m-d",(strtotime("{$today}")-3600*24*1));
        $time_24 = date("Y-m-d") . ' 00:00:00';
        $again = Db::table('up_reading_history')
            ->where('rhis_user_id',$user_id)
            ->where('rhis_game_id',$rg_id)
            ->order('rhis_time DESC')
            ->find();
        //-----------------
        $needscore = Db::table('up_sign_config')->where('id',3)->value('score');
        if($again && $again['rhis_type'] == 1 && $again['rhis_time'] >= $time_24){//如果是失败的再来一次，要扣金币的
            $myscore = Db::table('up_u_user')->where('user_id',$user_id)->value('user_integral');
            if($myscore < $needscore){
                return json(array('status' => 0, 'msg' => '您的金币不足'));
            }else{
                Db::table('up_u_user')->where('user_id',$user_id)->setDec('user_integral',$needscore);
                //丢金币入流转start-----
                $this->goldInOut ($user_id,$needscore,2,2);
                //丢金币入流转end-------
            }
        }
        //闯关获取题目时记录下此次闯关情况
        $this->gameHisJilu ($user_id,$rg_id);
        $data = Db::table('up_reading_subject')
            ->where('rs_game_id',$rg_id)
            ->where('rs_status',1)
            ->select();
        $game = Db::table('up_reading_game g')
            ->join ('up_coupon c','g.rg_coupon = c.coupon_id','LEFT')
            ->where('rg_id',$rg_id)
            ->field('rg_exp,rg_score,rg_order,c.coupon_name,c.coupon_price,c.coupon_id,c.coupon_use,c.coupon_online,c.coupon_status')
            ->find();
        // ----过期的优惠券不显示-----
        if($game['coupon_online'] != 1 || $game['coupon_status'] != 1){
            $game['coupon_price'] = '';
        }
        //-------------------------------------
        if($data){
            foreach ($data as $k=>$v){
                $anss = array('error','rs_a','rs_b','rs_c','rs_d');
                $int = rand(1,4);
                if($int == $v['rs_answer']){
                    $int = rand(1,4);
                }
                $answer = $anss[$v['rs_answer']]; // 正确答案的字段记录一下
                $right = $v[$answer]; // 正确答案
                $error = $v[$anss[$int]]; // 随机出来的错误答案
                //替换
                $data[$k][$anss[$int]] = $right;
                $data[$k][$answer] = $error;
                $data[$k]['rs_answer'] = $int;
            }
        }
        //-------------------------------------
        return json(array('status' => 200, 'msg' => $data, 'game' => $game, 'needscore' => $needscore));
    }
    /***
     * 某个关卡闯关成功：升级、以及是不是最后一关
     * rg_id：关卡的id
     * 阅读闯关
     */
    public function bookGamePass(){
        extract(input());
        $today = date('Y-m-d');
//        $rg_id = 3;$user_id=143;
        //------------------------以防万一进到此页（是否已通关）start----------------------
        $pass = Db::table('up_reading_game_pass')
            ->where('rgp_user_id',$user_id)
            ->where('rgp_game_id',$rg_id)
            ->find();
        if($pass){
            return json(array('status' => 0, 'msg' => '此关您已经通过了'));
        }
        //------------------------以防万一进到此页（是否已通关）start----------------------
        $game = Db::table('up_reading_game')->where('rg_id',$rg_id)->find();
        //------*************统计相关 start 闯关中***************------
        $ing = Db::table('up_reading_book_ing')
            ->where('rbp_user_id',$user_id)
            ->where('ing_book_id',$game['rg_rb_id'])
            ->find();
        if($ing){
            Db::table('up_reading_book_ing')
                ->where('rbp_user_id',$user_id)
                ->where('ing_book_id',$game['rg_rb_id'])
                ->update(['rbp_date'=>$today]);
        }else{
            Db::table('up_reading_book_ing')->insert(['rbp_user_id'=>$user_id,'ing_book_id'=>$game['rg_rb_id'],'rbp_date'=>$today]);
        }
        //------*************统计相关  end  闯关中***************------
        $exp1 = Db::table('up_u_user')->where('user_id',$user_id)->value('user_exp');
        $insert = array();
        $insert['rgp_book_id'] = $game['rg_rb_id'];
        $insert['rgp_game_id'] = $rg_id;
        $insert['rgp_user_id'] = $user_id;
        $insert['rgp_exp'] = $game['rg_exp'];
        $insert['rgp_score'] = $game['rg_score'];
        $level_before = Db::table('up_exp_level')
            ->where('el_min','<=',$exp1)
            ->order('el_level DESC')
            ->find();
        // 启动事务
        Db::startTrans();
        try{
            //--改成通关任意一关就可以干其他 start --
            Db::table('up_u_user')->where('user_id',$user_id)->setField('user_pass_one',2);
            //--改成通关任意一关就可以干其他  end  --
            Db::table('up_reading_game_pass')->insert($insert);
            Db::table('up_reading_game')->where('rg_id',$rg_id)->setInc('rg_num');
            $gameTrue = $this->getHonorForEvery ($user_id,1);
            if($gameTrue === false){
                $honor = '';
            }else{
                $honor = $gameTrue;
            }
            //1、先涨
            $this->addUserExp ($user_id,$game['rg_exp'],$game['rg_score'],1,$game['rg_coupon']);
            //得金币入流转start-----
            $this->goldInOut ($user_id,$game['rg_score'],2,1);
            //得金币入流转end-------
            //----------------------------------------记录修改start-----------------------------------------------
            $his = Db::table('up_reading_history')
                ->where('rhis_user_id',$user_id)
                ->where('rhis_game_id',$rg_id)
                ->order('rhis_time DESC')
                ->find();
            $coupon = Db::table('up_coupon')
                ->where('coupon_id',$game['rg_coupon'])->field('coupon_price,coupon_name')->find();
            $coupon_price = $coupon['coupon_price'];
            $hisupdate = [
                'rhis_game_pass'=>$his['rhis_game_pass']+1,
                'rhis_exp_all'=>$his['rhis_exp_all']+$game['rg_exp'],
                'rhis_score_all'=>$his['rhis_score_all']+$game['rg_score'],
                'rhis_type'=>2,
                'rhis_coupon'=>$coupon_price,
            ];
            Db::table('up_reading_history')
                ->where('rhis_id',$his['rhis_id'])
                ->update($hisupdate);
            //----------------------------------------记录修改end-------------------------------------------
            //3、是否是这本书也通关了（正好是最后一关）:此记录通关数
            $allgame = Db::table('up_reading_game')->where('rg_rb_id',$game['rg_rb_id'])->column('rg_id');
            $mygame = Db::table('up_reading_game_pass')
                ->where('rgp_book_id',$game['rg_rb_id'])
                ->where('rgp_user_id',$user_id)
                ->column('rgp_game_id');
            if($allgame == array_intersect($allgame, $mygame)){//此书通关
                //------*************统计相关 start 通关后把闯关中干掉***************------
                Db::table('up_reading_book_ing')
                    ->where('rbp_user_id',$user_id)
                    ->where('ing_book_id',$game['rg_rb_id'])
                    ->delete();
                //------*************统计相关  end  通关后把闯关中干掉***************------
                //---
                Db::table('up_reading_book')->where('rb_id',$game['rg_rb_id'])->setInc('rb_pass');
                //---
                $insert_book = array();
                $insert_book['rbp_user_id'] = $user_id;
                $insert_book['rbp_book_id'] = $game['rg_rb_id'];
                $insert_book['rbp_date'] = $today;
                Db::table('up_reading_book_pass')->insert($insert_book);
                $bookTrue = $this->getHonorForEvery ($user_id,2);
                if($bookTrue === false){
                    $honor = '';
                }else{
                    $honor = $bookTrue;
                }
                //----------------------------------------记录修改start-----------------------------------------------
                Db::table('up_reading_history')
                    ->where('rhis_id',$his['rhis_id'])
                    ->setInc('rhis_book_pass');
                //----------------------------------------记录修改end-----------------------------------------------
            }
            //2、是否升级(放到最后，因为要把关卡和书的先涨完再比)
            $newexp = Db::table('up_u_user')->where('user_id',$user_id)->value('user_exp');
            $level_up = $this->levelUp($user_id,$newexp,$level_before['el_level']);
            if($level_up === false){
                $shengji = '';
            }else{
                $shengji = $level_up;
            }
            $next_game = $this->getNextGame($game['rg_rb_id'],$user_id);
            // 提交事务
            Db::commit();
            $returnData['status'] = 200;
            $returnData['msg'] = '闯关成功';
            $returnData['honor'] = $honor;
            $returnData['shengji'] = $shengji;
            $returnData['next_game'] = $next_game;
            return json_encode($returnData);
        } catch (\Exception $e) {
            Db::rollback();
            return json_encode(['status'=>0,'msg'=>'失败']);
        }
    }
    //---------获取下一关id----------------------
    public function getNextGame($rb_id,$user_id)
    {
        $res = [
            'rb_id'=>$rb_id,
            'rg_id'=>10000
        ];
        $game = Db::table('up_reading_game')
            ->where('rg_rb_id',$rb_id)
            ->order('rg_order ASC')
            ->select();
        $mypass = Db::table('up_reading_game_pass')
            ->where('rgp_book_id',$rb_id)
            ->where('rgp_user_id',$user_id)
            ->column('rgp_game_id');
        $can = 0;
        if($game){
            foreach ($game as $k=>$v){
                if(!in_array($v['rg_id'],$mypass)){
                    $can++;
                    if($can == 1){
                        $res['rg_id'] = $v['rg_id'];
                    }
                }
            }
        }else{
            $res['rg_id'] = 0;
        }
        return $res;
    }
    //---------获取优惠券详情----------------------
    public function getCouponInfo()
    {
        extract(input());
        $data = Db::table('up_coupon')
            ->where('coupon_id',$coupon_id)
            ->field('coupon_id,coupon_name,coupon_thumb,coupon_price,coupon_content')
            ->find();
        return json_encode(['status'=>200,'msg'=>$data]);
    }
    /**
     * 错题记录：知识对战的错题记录
     */
    public function gameErrorRec()
    {
        extract(input());
        $today = date('Y-m-d H:i:s');
        $data = array();
        $data['er_user_id'] = $user_id;
        $data['er_fs_id'] = $rs_id;
        $have = Db::table('up_error_book')->where($data)->find();
        if($have){
            $update = [
                'er_time'=>$today,
                'er_num'=>$have['er_num']+1,
                'er_answer'=>$answer
            ];
            Db::table('up_error_book')->where($data)->update($update);
        }else{
            $data['er_answer'] = $answer;
            $data['er_time'] = $today;
            $data['er_num'] = 1;
            Db::table('up_error_book')->insert($data);
        }
        return json_encode(['status'=>200,'msg'=>'ok']);
    }
    /**
     * 图片上传至本地&压缩
     */
    public function uploadImg(){
        $file = request()->file('file');
        $yasuo = false;
        if (!$file->checkSize(100 * 1024)) { //大于100K就压缩一下
            $yasuo = true;
        }
        $dir = ROOT_PATH . 'public' . DS . 'uploads/images';
        if(!file_exists($dir)){
            //检查是否有该文件夹，如果没有就创建，并给予最高权限
            mkdir($dir, 0700,true);
        }
        $url =  "http://".$_SERVER['HTTP_HOST'];
        $info = $file->move($dir);
        if($info){
            $newName = $info->getSaveName();
            //压缩图片
            if ($yasuo === true) { //大于100K就压缩一下
                $this->image_png_size_add($dir . '/' . $newName, $dir . '/' . $newName);
            }
//            image_png_size_add(ROOT_PATH . 'public' . DS . 'uploads/images/'.$newName,ROOT_PATH . 'public' . DS . 'uploads/images/'.$newName);
            $msg = "{$url}/uploads/images/{$newName}";
            return json_encode(['status'=>200,'msg'=>$msg]);
        }else{
            $msg =  $file->getError();
            return json_encode(['status'=>200,'msg'=>$msg]);
        }
    }

    //清空我的各种闯关数据
    public function getHonorTenStatus()
    {
        extract(input());
        $ten = Db::table('up_u_user')->where('user_id',$user_id)->value('user_use_couple');
        if($ten == 2){
            Db::table('up_u_user')->where('user_id',$user_id)->setInc('user_use_couple',1);
            $honor = Db::table('up_honor')->where('id',10)->find();
            $couponID = $honor['coupon_id'];
            $coupon_name = Db::table('up_coupon')->where('coupon_id',$couponID)->field('coupon_name,coupon_price')->find();
            $honor['coupon_name'] = $coupon_name['coupon_name'];
            $honor['coupon_price'] = $coupon_name['coupon_price'];
            return json_encode(['status'=>200,'honor'=>$honor]);
        }else{
            return json_encode(['status'=>200,'honor'=>'']);
        }
    }
    /**
     * 压缩图片
     * @param $imgsrc:原图片地址（完整的图片路径）
     * @param $imgdst:压缩后的图片地址，也是完整的
     */
    function image_png_size_add($imgsrc,$imgdst){
        list($width,$height,$type)=getimagesize($imgsrc);
        switch($type){
            case 1:
                break;
            case 2:
                header('Content-Type:image/jpeg');
                $image = imagecreatefromjpeg($imgsrc);
                imagejpeg($image, $imgdst,50);
                imagedestroy($image);
                break;
            case 3:
                header('Content-Type:image/png');
                $image = imagecreatefrompng($imgsrc);
                imagejpeg($image, $imgdst,50);
                imagedestroy($image);
                break;
        }
    }
}